var app = getApp();
var goodsId;
var ztInfo;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectPick:"自提",
    checked:true,
    customer:{},
    obj:{},
    number:0,
    addressId:0,
    name:"",
    phone:"",
    address:"",
    disabled:false,
    isScore:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    goodsId=options.goodsId;
    this.setData({
      number:options.number
    })
    ztInfo={
      name:"",
      phone:"",
      address:"请至您的服务人员所属分部提货",
      addressId:999999,
    }
    var that = this;
    // 用户信息
    wx.request({
      url: app.getUrl() + '/api/customer/getCustomer',
      data:{
        customerId: app.globalData.customerId 
      },
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success(res) {
        if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
          ztInfo.name=res.data.obj.customerName;
          ztInfo.phone=res.data.obj.telPhone;
          that.setData({
            customer:res.data.obj,
          })
          // 商品详情
          wx.request({
            url: app.getUrl() + '/api/mall/goods_detail',
            data:{
              giftId: goodsId,
              Authorization: app.globalData.customerId + ":" + app.globalData.accessToken,
            },
            method: 'GET',
            success(res) {
              if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
                if(res.data.obj.limitNum==0){
                  res.data.obj.limitNum='不限'
                }
                that.setData({
                  obj:res.data.obj,
                  selectPick:res.data.obj.isPickUpSelf==true?'自提':'快递'
                })
                //如果是自提
                if(res.data.obj.isPickUpSelf){
                  that.setData({
                    name:ztInfo.name,
                    phone:ztInfo.phone,
                    address:ztInfo.address,
                    addressId:ztInfo.addressId,
                  })
                }else{
                  that.getAddressList()
                }
                if(res.data.obj.goodsSubscribeInfo && res.data.obj.goodsSubscribeInfo.goodsSubscribStatus=='正在热销' && res.data.obj.goodsSubscribeInfo.goodsSubscribMoney==0){
                  that.setData({
                    isScore:true
                  })
                }else if(res.data.obj.goodsMoney==0){
                  that.setData({
                    isScore:true
                  })
                }else{
                  that.setData({
                    isScore:false
                  })
                }
              }else{
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            },
            fail(res) {
              console.log(res)
              wx.showToast({
                title: '连接服务器失败',
                icon: 'none',
                duration: 2000
              })
            }
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail(res) {
        console.log(res)
        wx.showToast({
          title: '连接服务器失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.addressId!=ztInfo.addressId && this.data.addressId!=0){
      this.getAddress()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      disabled:false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      disabled:false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  selectOne(){
    wx.showToast({
      title: '当前商品仅支持'+this.data.selectPick,
      icon: 'none',
      duration: 2000
    })
  },
  selectPick(){
    if(this.data.selectPick=='快递'){
      wx.navigateTo({
        url: '../xzdz/xzdz?from=select',
      })
    }
  },
  getAddress(){
    var that = this;
    wx.request({
      url: app.getUrl() + '/api/receive_info/receive_info',
      data:{
        infoId: this.data.addressId,
        Authorization: app.globalData.customerId + ":" + app.globalData.accessToken,
      },
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success(res) {
        if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
          that.setData({
            name:res.data.obj.receiverName,
            phone:res.data.obj.receiverPhone,
            address:res.data.obj.receiverRegion+res.data.obj.receiverAddr
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail(res) {
        console.log(res)
        wx.showToast({
          title: '连接服务器失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  getAddressList(){
    var that = this;
    wx.request({
      url: app.getUrl() + '/api/receive_info/receive_infos',
      data:{
        pageIndex:1,
        pageSize:10,
        Authorization: app.globalData.customerId + ":" + app.globalData.accessToken,
      },
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success(res) {
        if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
          if(res.data.obj.total>0){
            that.setData({
              addressId:res.data.obj.rows[0].infoId,
              name:res.data.obj.rows[0].receiverName,
              phone:res.data.obj.rows[0].receiverPhone,
              address:res.data.obj.rows[0].receiverRegion+res.data.obj.rows[0].receiverAddr,
            })
          }else{
            wx.showToast({
              title: '暂无地址，快去添加一个吧',
              icon: 'none',
              duration: 2000
            })
          }
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail(res) {
        console.log(res)
        wx.showToast({
          title: '连接服务器失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  switchChange(e){
    this.setData({
      checked:e.detail.value
    })
  },
  buy(e){
    var that = this;
    if(this.data.addressId==0){
      wx.showToast({
        title: '请选择地址',
        icon: 'none',
        duration: 2000
      })
    }else{
      this.setData({
        disabled:true
      })
      wx.request({
        url: app.getUrl() + '/api/order_info/create_order',
        data:{
          infoId: this.data.addressId,
          buyCount:this.data.number,
          goodsId:goodsId,
          isUseIntegral:this.data.checked,
          formId: e.detail.formId,
          Authorization: app.globalData.customerId + ":" + app.globalData.accessToken,
        },
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        success(res) {
          console.log(res)
          if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
            //如果全部使用积分支付，则直接支付成功
            if(res.data.obj.payMoney==0 && res.data.obj.orderStatus=='支付成功'){
              wx.showToast({
                title: '支付成功',
                icon: 'success',
                duration: 2000
              })
              setTimeout(function(){
                wx.redirectTo({
                  url: '../myOrder/myOrder',
                })
              },2000)
            }else{
              var orderId=res.data.obj.orderId;
              //否则要使用微信支付
              wx.login({
                success(res){
                  if (res.code){
                    //小程序预支付
                    wx.request({
                      url: app.getUrl() + '/api/order_info/wexcx_prepare_pay',
                      data:{
                        orderId: orderId,
                        code:res.code,
                        // Authorization: app.globalData.customerId + ":" + app.globalData.accessToken,
                      },
                      method: 'POST',
                      header: {
                        "Content-Type": "application/x-www-form-urlencoded",
                      },
                      success(res) {
                        console.log(res)
                        if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
                          wx.requestPayment({
                            timeStamp: res.data.obj.timeStamp,
                            nonceStr: res.data.obj.nonceStr,
                            package: res.data.obj.wepaypackage,
                            signType: res.data.obj.signType,
                            paySign: res.data.obj.paySign,
                            success: function (res) {
                              if (res.errMsg == "requestPayment:ok") {
                                //获取支付信息
                                wx.showToast({
                                  title: '支付成功',
                                  icon: 'success',
                                  duration: 2000
                                })
                                setTimeout(function(){
                                  wx.redirectTo({
                                    url: '../myOrder/myOrder',
                                  })
                                },2000)
                              }else{
                                that.setData({
                                  disabled:false
                                })
                                console.log(res)
                                wx.showToast({
                                  title: '支付失败',
                                  icon: 'none',
                                  duration: 2000
                                })
                              }
                            },
                            fail: function (res) {
                              that.setData({
                                disabled:false
                              })
                              console.log(res)
                              if(res.errMsg == "requestPayment:fail cancel"){
                                wx.redirectTo({
                                  url: '../myOrder/myOrder?select=待付款',
                                })
                              }
                              wx.showToast({
                                title: '支付失败',
                                icon: 'none',
                                duration: 2000
                              })
                            },
                          })
                        }else{
                          that.setData({
                            disabled:false
                          })
                          wx.showToast({
                            title: res.data.msg,
                            icon: 'none',
                            duration: 2000
                          })
                        }
                      },
                      fail(res) {
                        that.setData({
                          disabled:false
                        })
                        console.log(res)
                        wx.showToast({
                          title: '连接服务器失败',
                          icon: 'none',
                          duration: 2000
                        })
                      }
                    })
                  }else{
                    that.setData({
                      disabled:false
                    })
                    wx.showToast({
                      title: '获取用户登录态失败',
                      icon: 'none',
                      duration: 2000
                    })
                    console.log('获取用户登录态失败！' + res.errMsg)
                  }
                },
                fail: function (res) {
                  that.setData({
                    disabled:false
                  })
                  wx.showToast({
                    title: '微信登录失效，请重新登录',
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            }
          }else{
            that.setData({
              disabled:false
            })
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail(res) {
          console.log(res)
          that.setData({
            disabled:false
          })
          wx.showToast({
            title: '连接服务器失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  }
})